package log

import (
	"fmt"
	"io"
	"os"
	"sync"

	"gitee.com/ironCoffers/goHelper/log/base"

	"gitee.com/ironCoffers/goHelper/log/logrus"
)

//LoggerCreator 代表日志记录器的创建器
type LoggerCreator func(level base.LogLevel, format base.LogFormat, writer io.Writer, options []base.Option) base.BaseLogger

//loggerCreatorMap 代表日志记录器创建器的映射
var loggerCreatorMap = map[base.LoggerType]LoggerCreator{}

//logMutex 代表日志记录器创建器映射的专用锁
var logMutex sync.RWMutex

//RegisterLogger 用于注册日志记录器
func RegisterLogger(loggerType base.LoggerType, creator LoggerCreator, cover bool) error {
	if loggerType == "" {
		return fmt.Errorf("looger register error: invalid looger type")
	}
	if creator == nil {
		return fmt.Errorf("logger register error: invalid logger creator (logger type: %s)", loggerType)
	}
	logMutex.Lock()
	defer logMutex.Unlock()
	if _, ok := loggerCreatorMap[loggerType]; ok || !cover {
		return fmt.Errorf("logger register error: already existing logger for type %q", loggerType)
	}
	loggerCreatorMap[loggerType] = creator
	return nil
}

func Logger(loggerType base.LoggerType, level base.LogLevel, format base.LogFormat, writer io.Writer, options []base.Option) base.BaseLogger {
	var logger base.BaseLogger

	logMutex.RLock()
	creator, ok := loggerCreatorMap[loggerType]
	logMutex.RUnlock()
	if ok {
		logger = creator(level, format, writer, options)
	} else {
		logger = logrus.NewLoggerBy(level, format, writer, options)
	}
	return logger
}

//DLogger 返回一个新的默认的日志记录器
func DLogger() base.BaseLogger {
	return Logger(
		base.TYPE_LOGRUS,
		base.LEVEL_INFO,
		base.FORMAT_TEXT,
		os.Stdout,
		nil)
}
